api.ts ➔ gAuth   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 16
rs 9.9
c 0
b 0
f 0
cc 1
1
import {chat, auth} from '@googleapis/chat';
2
import {GaxiosResponse} from 'gaxios/build/src/common';
3
4
/**
5
 * Create google api credentials
6
 *
7
 * @returns {object} google.chat
8
 */
9
function gAuth() {
10
  // Use default credentials (service account)
11
  const credentials = new auth.GoogleAuth({
12
    // keyFile: path.join(__dirname, '../../tests/creds.json'),
13
    scopes: ['https://www.googleapis.com/auth/chat.bot'],
14
  });
15
16
  return chat({
17
    version: 'v1',
18
    auth: credentials,
19
  });
20
}
21
22
/**
23
 * Call Google API using default credentials (service account)
24
 *
25
 * @param {string} action - request action(create,update,get,delete)
26
 * @param {object} request - request body
27
 * @returns {Promise<GaxiosResponse | {status: number, statusText: string, data: object}>} Response from google api
28
 */
29
export async function callMessageApi(
30
  action: string, request: object): Promise<GaxiosResponse | {status: number, statusText: string, data: object}> {
31
  const chatApi = gAuth();
32
  let response;
33
34
  try {
35
    if (action === 'create') {
36
      response = await chatApi.spaces.messages.create(request);
37
    } else if (action === 'update') {
38
      response = await chatApi.spaces.messages.update(request);
39
    } else if (action === 'get') {
40
      response = await chatApi.spaces.messages.get(request);
41
    }
42
  } catch (error) {
43
    // @ts-ignore: all error should have this method
44
    const errorMessage = error.message ?? error.toString() ?? 'Unknown error';
45
    console.error('Error:', action, JSON.stringify(request), response, errorMessage);
46
    response = {'status': 444, 'statusText': errorMessage, 'data': {}};
47
  }
48
49
  if (!response) {
50
    throw new Error('Empty response');
51
  }
52
53
  return response;
54
}
55